//
//  IGFindViewController.m
//  iGameApp
//
//  Created by lanou on 16/1/9.
//  Copyright © 2016年 WYC. All rights reserved.
//

#import "IGFindViewController.h"
#import "IGFindMainTBVHeadView.h"
#import "IGFindMainTableViewCell.h"
#import "IGFindMainTBVModel.h"
#import "IGFindMainHeadTopModel.h"
#import "IGFindMainHeadMiddleModel.h"
#import "IGFindSearchViewController.h"
#import "IGFindSearchContentTBVController.h"
#import "IGFindRadioPlayViewController.h"

@interface IGFindViewController () <UITableViewDataSource, UITableViewDelegate,UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) NSMutableArray *headTopArray;
@property (nonatomic, strong) NSMutableArray *headMiddleArray;
@property (nonatomic, strong) IGFindMainTBVHeadView *headView;
@property (nonatomic, strong) IGCustomNavigationController *navc;
// 用于刷新
@property (nonatomic, assign) NSInteger refreshCount;
@property (nonatomic, strong) ss_customSearchBar *searchBar;
@property (nonatomic, strong) IGFindSearchContentTBVController *searchContentVC;
@property (nonatomic, strong) NSMutableArray *searchContentArray;


@end

@implementation IGFindViewController

-(void)dealloc
{
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center removeObserver:self forKeyPath:@"closeUserInteractionEnabled"];
    [center removeObserver:self forKeyPath:@"openUserInteractionEnabled"];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    _headView = [[UINib nibWithNibName:@"IGFindMainTBVHeadView" bundle:nil] instantiateWithOwner:self options:nil].firstObject;
    _headView.frame = CGRectMake(0, 0, 0, 350);
    _tableView.tableHeaderView = _headView;
    [_tableView registerNib:[UINib nibWithNibName:@"IGFindMainTableViewCell" bundle:nil] forCellReuseIdentifier:@"IGFindMainTableViewCell"];
    _tableView.rowHeight = 93;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.autoresizesSubviews = NO;
    
    // 请求数据
    _refreshCount = 0;
    _dataArray = [NSMutableArray array];
    _headTopArray = [NSMutableArray array];
    _headMiddleArray = [NSMutableArray array];
    [self requestHeadViewData];
    [self requestTableViewData];
    
    // 导航栏
    _navc = (IGCustomNavigationController *)self.navigationController;
    [self addSearchView];
    
    [_headView.changeButton addTarget:self action:@selector(changeDataButton) forControlEvents:(UIControlEventTouchUpInside)];
    
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(closeNotification) name:@"closeUserInteractionEnabled" object:nil];
    [center addObserver:self selector:@selector(openNotification) name:@"openUserInteractionEnabled" object:nil];
}

- (void)closeNotification
{
    for (int i = 0; i < 9; i++) {
        UIButton *button = (UIButton *)[_headView viewWithTag:100 + i];
        button.userInteractionEnabled = NO;
    }
    
    for (int i = 0; i < 3; i++) {
        UIButton *button = (UIButton *)[_headView viewWithTag:200 + i];
        button.userInteractionEnabled = NO;
    }
    _tableView.userInteractionEnabled = NO;
    _headView.changeButton.userInteractionEnabled = NO;
}

- (void)openNotification
{
    for (int i = 0; i < 9; i++) {
        UIButton *button = (UIButton *)[_headView viewWithTag:100 + i];
        button.userInteractionEnabled = YES;
    }
    
    for (int i = 0; i < 3; i++) {
        UIButton *button = (UIButton *)[_headView viewWithTag:200 + i];
        button.userInteractionEnabled = YES;
    }
    _tableView.userInteractionEnabled  = YES;
    _headView.changeButton.userInteractionEnabled = YES;
}

- (void)viewWillAppear:(BOOL)animated
{
    [UIView animateWithDuration:.3 animations:^{
        _searchBar.frame = CGRectMake(80, 7, kScreenWidth - 100, 30);
    }];
    _searchBar.textView.text = @"";
    [_searchBar endEditing:YES];
    _searchBar.hidden = NO;
    _navc.iconButton.hidden = NO;
    _searchBar.textView.delegate = self;
}

- (void)viewWillDisappear:(BOOL)animated
{
    _navc.iconButton.hidden = YES;
}

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    _tableView.frame = CGRectMake(0, 64, kScreenWidth, kScreenHeight - 108);
    [self refresh];
}

// 上拉刷新, 下拉加载
- (void)refresh
{
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _refreshCount = 0;
        [self requestHeadViewData];
        [self requestTableViewData];
    }];
    
        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            _refreshCount += 10;
            [self requestTableViewData];
        }];
}

- (void)requestHeadViewData
{
    [_headTopArray removeAllObjects];
    [IGAFNetworking requestWithUrlString:@"http://www.imbatv.cn/api_2_4_0/findHotVideos" parDic:nil metho:GET finish:^(NSDictionary *dataDic) {
        if ([dataDic[@"message"] isEqualToString:@"失败"]) {
            return;
        }
        for (NSDictionary *dic in dataDic[@"data"]) {
            IGFindMainHeadTopModel *model = [[IGFindMainHeadTopModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [_headTopArray addObject:model];
        }
        [_tableView.mj_header endRefreshing];
        [self setUpDataForHeadTopView];
    } error:^(NSError *requestError) {
        NSLog(@"请求错误");
    }];
    
    [_headMiddleArray removeAllObjects];
    [IGAFNetworking requestWithUrlString:@"http://www.imbatv.cn/api_2_4_0/getTagsRandom" parDic:nil metho:GET finish:^(NSDictionary *dataDic) {
        if ([dataDic[@"message"] isEqualToString:@"失败"]) {
            return;
        }
        for (NSDictionary *dic in dataDic[@"data"]) {
            IGFindMainHeadMiddleModel *model = [[IGFindMainHeadMiddleModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [_headMiddleArray addObject:model];
        }
        [_tableView.mj_header endRefreshing];
        [self setUpDataForHeadMiddleView];
    } error:^(NSError *requestError) {
        NSLog(@"请求错误");
    }];
}

- (void)requestTableViewData
{
    NSString *strUrl = [NSString stringWithFormat:@"http://www.imbatv.cn/api_2_4_0/getFindVideos?num=10&start=%ld",_refreshCount];
    if (_refreshCount == 0) {
        [_dataArray removeAllObjects];
    }
    [IGAFNetworking requestWithUrlString:strUrl parDic:nil metho:GET finish:^(NSDictionary *dataDic) {
        if ([dataDic[@"message"] isEqualToString:@"失败"]) {
            return;
        }
        for (NSDictionary *dic in dataDic[@"data"]) {
            IGFindMainTBVModel *model = [[IGFindMainTBVModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [_dataArray addObject:model];
        }
        if (_dataArray.count < _refreshCount + 10) {
            [_tableView.mj_footer endRefreshingWithNoMoreData];
        }else {
            [_tableView.mj_footer endRefreshing];
        }
        [_tableView.mj_header endRefreshing];
        
        [_tableView reloadData];
    } error:^(NSError *requestError) {
        NSLog(@"请求错误");
    }];
}

#pragma tableView dataSource
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    IGFindMainTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"IGFindMainTableViewCell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (_dataArray.count != 0) {
        IGFindMainTBVModel *model = _dataArray[indexPath.row];
        cell.model = model;
    }
     return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    IGFindRadioPlayViewController *radioPlayVC = [[IGFindRadioPlayViewController alloc] init];
    IGFindMainTBVModel *model = _dataArray[indexPath.row];
    radioPlayVC.vid = model.vid;
    radioPlayVC.isFindPushHere = YES;
   
    [[IGHistoryList defaultIGHistoryList] saveDataAtLoacllyWithTitle:model.title img:model.image vid:model.vid];
    
    [self.navigationController pushViewController:radioPlayVC animated:YES];
}

// 给主页面表头上的button赋值
- (void)setUpDataForHeadMiddleView
{
    for (int i = 0; i < 9; i++) {
        UIButton *button = (UIButton *)[_headView viewWithTag:100 + i];
        IGFindMainHeadMiddleModel *model = _headMiddleArray[i];
        [button setTitle:model.tag_name forState:(UIControlStateNormal)];
        [button addTarget:self action:@selector(headMiddleButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    }
}
- (void)setUpDataForHeadTopView
{
    for (int i = 0; i < 3; i++) {
        UIButton *button = (UIButton *)[_headView viewWithTag:200 + i];
        IGFindMainHeadTopModel *model = _headTopArray[i];
        [button sd_setBackgroundImageWithURL:[NSURL URLWithString:model.img] forState:(UIControlStateNormal) placeholderImage:nil];
        [button addTarget:self action:@selector(headTopButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    }
}

- (void)headMiddleButtonClick:(UIButton *)sender
{
    NSInteger index = sender.tag - 100;
    IGFindMainHeadMiddleModel *model = _headMiddleArray[index];
    NSString *buttonName = model.tag_name;
    [self accordingWordSearchAndJumpContentVC:buttonName];
}

// 跳转页面
- (void)accordingWordSearchAndJumpContentVC:(NSString *)buttonName
{
        // 初始化搜索完展示内容的VC
    _searchContentVC = [[IGFindSearchContentTBVController alloc] init];
    // 下拉刷新
    _searchContentVC.pushHere = MainMiddleButton;
    _searchContentVC.titleName = buttonName;
    _searchContentVC.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self requestSearchResultData:buttonName];
    }];
    [_searchContentVC.tableView.mj_header beginRefreshing];
    _searchBar.hidden = YES;
    [self.navigationController pushViewController:_searchContentVC animated:YES];
}
// 请求数据
- (void)requestSearchResultData:(NSString *)searchContent
{
    _searchContentArray = [NSMutableArray array];
    NSString *UTFstring = [searchContent stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *urlString = [NSString stringWithFormat:@"http:www.imbatv.cn/api_2_4_0/GetSearchResult?key=%@&num=10&start=0",UTFstring];
    [IGAFNetworking requestWithUrlString:urlString parDic:nil metho:GET finish:^(NSDictionary *dataDic) {
        if ([dataDic[@"message"] isEqualToString:@"没有查询数据"]) {
            return;
        }
        for (NSDictionary *dic in dataDic[@"data"]) {
            // 共用主页面tableView的model
            IGFindMainTBVModel *model = [[IGFindMainTBVModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [_searchContentArray addObject:model];
        }
        _searchContentVC.dataArray = _searchContentArray;
        // 结束刷新
        [_searchContentVC.tableView.mj_header endRefreshing];
        [_searchContentVC.tableView reloadData];
    } error:^(NSError *requestError) {
        
    }];
}

- (void)headTopButtonClick:(UIButton *)sender
{
    IGFindRadioPlayViewController *radioPlayVC = [[IGFindRadioPlayViewController alloc] init];
    IGFindMainHeadTopModel *model = _headTopArray[sender.tag - 200];
    radioPlayVC.vid = model.vid;
    radioPlayVC.isFindPushHere = YES;
    [self.navigationController pushViewController:radioPlayVC animated:YES];
}

- (void)changeDataButton
{
    [self requestHeadViewData];
}

// 添加搜索框
- (void)addSearchView
{
    _searchBar = [[ss_customSearchBar alloc] initWithFrame:CGRectMake(80, 5, kScreenWidth - 100, 33)];
    _searchBar.layer.cornerRadius = 5;
    _searchBar.backgroundColor = [[UIColor grayColor] colorWithAlphaComponent:.3];
    _searchBar.tag = 1000;
    [_navc.bgView addSubview:_searchBar];
}

#pragma mark  --- UITextView代理方法
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    IGFindSearchViewController *searchVC = [[IGFindSearchViewController alloc] init];
    searchVC.searchBar = _searchBar;
    [self.navigationController pushViewController:searchVC animated:NO];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
